import React, { useEffect, useState } from 'react';
import {
  View, StyleSheet, RefreshControl, TouchableOpacity, Dimensions, FlatList, Text
} from 'react-native';

import { Tip } from 'beeshell';
import AntDesign from 'react-native-vector-icons/AntDesign';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import Http from '../../service/http';
import requestCheck from '../../utils/RequestCheckUtil';
import BpmnUtil from '../../utils/BpmnUtil';
import { Card, Text as CustomText } from '../../components';
import { sizes, colors } from '../../constants/theme';
import { historyTaskStatus } from '../../configs/status';
import DataUtil from '../../utils/DataUtil';


const renderType = (type) => (
  <FontAwesome5
    name={type === 'auto' ? 'robot' : 'user'}
    size={12}
    color={type === 'auto' ? 'green' : colors.secondary}
  />
);

const renderItem = ({ item }, width, navigation, historyId) => {
  const { status, name, type } = item;
  const [taskName, taskId] = DataUtil.parseName(name);
  const { state: { params: { processName } } } = navigation;
  const icon = historyTaskStatus[status];
  const handlePress = () => {
    if (status === 0) {
      Tip.show('该任务尚未开始');
    } else {
      navigation.navigate(
        'ProcessMonitor',
        { historyId, taskId: item.id, processName }
      );
    }
  };

  return (
    <TouchableOpacity
      key={item.id}
      onPress={handlePress}
    >
      <Card
        center
        middle
        shadow
        style={{
          minWidth: (width - (sizes.padding * 2.4) - sizes.base) / 2,
          maxWidth: (width - (sizes.padding * 2.4) - sizes.base) / 2,
          maxHeight: (width - (sizes.padding * 2.4) - sizes.base) / 2,
          marginHorizontal: sizes.base
        }}
      >
        <CustomText medium height={20}>{taskName}</CustomText>
        <CustomText medium size={12}>{taskId}</CustomText>
        <View style={{
          flexDirection: 'row',
          justifyContent: 'center',
          marginVertical: sizes.sperate
        }}
        >
          <AntDesign
            name={icon.iconName}
            size={sizes.base}
            style={{ color: icon.color }}
          />
          <Text style={{ fontSize: sizes.base, marginHorizontal: 5 }}>
            {icon.name}
          </Text>
        </View>
        <CustomText gray caption>
          工序
          {renderType(type)}
        </CustomText>
      </Card>
    </TouchableOpacity>
  );
};

// 流程详情
export default function ProcessDetail({ navigation }) {
  const { state: { params: { historyId, processId } } } = navigation;
  const [taskList, setTaskList] = useState([]);
  const { width } = Dimensions.get('window');

  const [refresh, setRefresh] = useState(0);
  const [isLoading, setIsLoading] = useState(false);

  const merge = (status, tasks) => {
    tasks.forEach((i) => {
      const { id } = i;
      for (let index = 0; index < status.length; index += 1) {
        if (status[index][id]) {
          i.status = status[index][id];
          break;
        }
        i.status = 0;
      }
    });
  };

  useEffect(() => {
    async function fetchData() {
      setIsLoading(true);
      const res1 = await Http.inquireHistoryStatus({ historyId });
      let status;
      const callback1 = ({ taskStatus }) => { status = taskStatus; };
      requestCheck(res1, callback1, navigation);
      const res2 = await Http.inquireProcess({ processId });
      let list;
      const callback2 = ({ bpmn }) => { list = BpmnUtil.parseXML(bpmn); };
      requestCheck(res2, callback2, navigation);
      merge(status, list);
      setTaskList(list);
      setIsLoading(false);
    }
    fetchData();
  }, [historyId, navigation, processId, refresh]);

  return (
    <View style={styles.container}>
      <FlatList
        style={{
          paddingVertical: sizes.base,
          marginBottom: sizes.base * 3.5,
        }}
        data={taskList}
        numColumns={2}
        renderItem={(item) => renderItem(item, width, navigation, historyId)}
        keyExtractor={(item) => `${item.id}`}
        refreshControl={(
          <RefreshControl
            title="加载中"
            titleColor={colors.secondary}
            colors={[colors.primary, colors.secondary]}
            tintColor={colors.primary}
            refreshing={isLoading}
            onRefresh={() => setRefresh(refresh + 1)}
          />
        )}
      />
    </View>
  );
}

// 根据流程名字确定 该页面的 title
ProcessDetail.navigationOptions = {
  title: '工序'
};

const styles = StyleSheet.create({
  header: {
    padding: sizes.base
  },
  container: {
    flex: 1
  }
});
